// app.js
var httpUtil = require('utils/httpUtil.js');
var uiUtil = require('utils/uiUtil.js');
var QQMapWX = require('utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
var key ="QR7BZ-UDZ3R-SS7WQ-WLPBD-76352-5YBB5";
var that

App({
  globalData: {
    loginStatus: 0, //登录状态，0：正在登录，1:登录失败，2：登录成功
    loginToken: null,
    sessionKey:null,

    pages:true,
    mchId:null,

    userLocationStatus: 0,//用户位置状态，0：正在获取，1获取失败，2：获取成功，3：用户未授权
    userLocation:null, //用户地理位置

    userInfo:null, //用户信息
    userPhone:null //用户手机号
  },
  onLaunch: function (options) {
    that = this;
    //检查更新
    that.checkUpgrade();
    that.getAuthorization();
  },

  /**
   * 登录请求
   */
  loginRequest(code, wxOfficialCode) {
    httpUtil.PostRequest("small_login", {
      wxLoginCode: code,
      wxOfficialCode: wxOfficialCode
    }, {
      success(res) {
        that.globalData.pages = res.auditFlag;
        that.globalData.authorizeFlag = res.authorizeFlag;
        that.globalData.mchId = res.mchId;
        that.globalData.loginToken = res.token;
        that.globalData.sessionKey = res.sessionKey;
        that.globalData.memKey = res.memKey;
        that.globalData.loginStatus = 2;
      },
      fail(code, res) {
        uiUtil.showToast(res);
        that.globalData.loginStatus = 1
      },
      complete() {
        setTimeout(function() {
          if (that.loginRequestReadyCallback) {
            that.loginRequestReadyCallback()
          }
        }, 800)
      }
    })
  },

  /**
   * 监听用户是否授权地理位置
   */
  getAuthorization:function(){
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != true) {
            wx.authorize({
              scope: 'scope.userLocation',
              success() {
                // 用户已经同意小程序使用地理位置功能，后续调用不会弹窗询问
                that.getLocation();
              },
              fail(){
                //用户拒绝授权
                that.globalData.userLocationStatus = 3;
              }
            })
        } else {
          //调用wx.getLocation的API
          that.getLocation();
        }

      }
    })
  },

  /**
   * 获取用户地理位置
   */
  getLocation:function(){
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy:true,
      highAccuracyExpireTime:4000,
      success(res) {
        qqmapsdk = new QQMapWX({
          key: key
        });
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          get_poi:1,
          poi_options:"policy=2;radius=100;page_size=1;page_index=1",
          success: function (res) {
            if(res.result.pois[0].ad_info.adcode!="371602"){ //判断是否在滨州市
              res.result.pois[0].title="滨州市";
              res.result.pois[0].location.lat=37.38211;
              res.result.pois[0].location.lng=117.97279;
            }
            
            that.globalData.userLocation = res.result;
            that.globalData.userLocationStatus = 2;
          },
          fail: function (res) {
            that.globalData.userLocationStatus = 1;
          },
          complete() {
            uiUtil.hideLoading();
            setTimeout(function () {
              if (that.locationRequestReadyCallback) {
                that.locationRequestReadyCallback()
              }
            }, 800)
          }
        });

      },
      fail(res){
        uiUtil.hideLoading();
        that.globalData.userLocationStatus = 1;
      }

    })
  },

  /**
   * 返回上一页
   */
  lastPage() {
    var pages = getCurrentPages();
    var lastPage = pages[pages.length - 2];
    lastPage.onResultRegisterSuccess();
    wx.navigateBack({
      delta: 1,
    });
  },

  /**
   * 检测升级
   */
  checkUpgrade() {
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function(res) {
      // 请求完新版本信息的回调
      if (res.hasUpdate) {
        uiUtil.showToast("发现新版本，即将更新后重启")
        updateManager.onUpdateReady(function() {
          // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
          updateManager.applyUpdate()
        })
        updateManager.onUpdateFailed(function() {
          // 新的版本下载失败
          wx.showModal({
            title: '已经有新版本了哟~',
            content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
          })
        })
      }
    })
  }
})
